package com.example.james.fragmentbestpractice;

import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.TextView;

import java.util.List;

/**
 * Created by James on 1/25/2018.
 */

public class NewsTitleAdapter extends RecyclerView.Adapter<NewsTitleAdapter.ViewHolder> {

    private List<News> newsList;
    private boolean isTwoPage;
    private FragmentManager fragmentManager;

    @Override
    public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
        final ViewHolder viewHolder = new ViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                News news = newsList.get(viewHolder.getAdapterPosition());
                if (isTwoPage){
                    ViewParent r = parent.getParent();
                    NewsContentFragment newsContentFragment = (NewsContentFragment) ((MainActivity) parent.getContext()).getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
//                    NewsContentFragment newsContentFragment = (NewsContentFragment) fragmentManager.findFragmentById(R.id.news_content_fragment);
                    newsContentFragment.refresh(news.getTitle(), news.getContent());
                } else {
                    NewsContentActivity.actionStart(parent.getContext(), news.getTitle(), news.getContent());
                }
            }
        });
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        News news = newsList.get(position);
        holder.titleTextView.setText(news.getTitle().toString());
    }

    @Override
    public int getItemCount() {
        return newsList.size();
    }

    public NewsTitleAdapter(List<News> newsList, boolean isTwoPage, FragmentManager fragmentManager) {
        this.newsList = newsList;
        this.isTwoPage = isTwoPage;
        this.fragmentManager = fragmentManager;
    }

    public NewsTitleAdapter(List<News> newsList, boolean isTwoPage) {
        this.newsList = newsList;
        this.isTwoPage = isTwoPage;
    }

    public NewsTitleAdapter(List<News> newsList) {
        this.newsList = newsList;
    }

    static class ViewHolder extends RecyclerView.ViewHolder{

        TextView titleTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            titleTextView = itemView.findViewById(R.id.news_title);
        }
    }
}
